package org.moflon.moca;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.BasicConfigurator;
import org.eclipse.emf.ecore.EObject;
import org.moflon.moca.blocks.parser.BlocksParserAdapter;
import org.moflon.moca.blocks.unparser.BlocksUnparserAdapter;
import org.moflon.util.TranslatorHelper;
import org.moflon.util.eMoflonEMFUtil;

import BlockCodeAdapter.BlockCodeAdapterPackage;
import BlockLanguage.BlockLanguagePackage;
import Moca.CodeAdapter;
import Moca.MocaFactory;
import MocaTree.Folder;
import MocaTree.MocaTreePackage;
import TGGLanguage.TGGLanguagePackage;
import TGGLanguage.algorithm.ApplicationTypes;

public class MocaMain {

	private static CodeAdapter codeAdapter;

	public static void main(String[] args) throws IOException {
		BasicConfigurator.configure();

		// Register parsers and unparsers
		codeAdapter = MocaFactory.eINSTANCE.createCodeAdapter();
		codeAdapter.getParser().add(new BlocksParserAdapter());
		codeAdapter.getUnparser().add(new BlocksUnparserAdapter());

		textToModel();

		//modelToText();
	}

	private static void modelToText() throws IOException {
		// Perform model-to-tree (backward)
		TranslatorHelper helper = new TranslatorHelper();
		helper.setInputModel(MocaTreePackage.eINSTANCE, "./instances/out/blocks.xmi");
		helper.setOutputModel(BlockLanguagePackage.eINSTANCE,
				"./instances/tree_backward.xmi");
		helper.setCorrModel(BlockCodeAdapterPackage.eINSTANCE,
				"./instances/out/corr_backward.xmi");
		helper.setDirection(ApplicationTypes.BACKWARD);
		helper.setStaticAnalysis("model/BlockCodeAdapter.gen.sma.xmi");

		helper.integrate();
		
		// Save tree to file
		MocaTree.File tree = (MocaTree.File)helper.getOutputRoot();

		// Perform tree-to-text (using initial tree)
		codeAdapter.unparseFile(tree, new File("instances/in"));
	}

	private static void textToModel() throws IOException {
		// Perform text-to-tree
		MocaTree.File tree = codeAdapter.parseFile(new File(
				"instances/in/test.blocks"), null);

		// Save tree to file
		eMoflonEMFUtil.saveModel(MocaTreePackage.eINSTANCE, tree,
				"instances/tree_forward.xmi");

		// Perform tree-to-model (forward)
		TranslatorHelper helper = new TranslatorHelper();
		helper.setInputModel(MocaTreePackage.eINSTANCE, "./instances/tree_forward.xmi");
		helper.setOutputModel(BlockLanguagePackage.eINSTANCE,
				"./instances/out/blocks.xmi");
		helper.setCorrModel(BlockCodeAdapterPackage.eINSTANCE,
				"./instances/out/corr_forward.xmi");
		helper.setDirection(ApplicationTypes.FORWARD);
		helper.setStaticAnalysis("model/BlockCodeAdapter.gen.sma.xmi");
				
		helper.integrate();
		
		eMoflonEMFUtil.saveModel(TGGLanguagePackage.eINSTANCE, helper.getTranslationProtocol(), "instances/protocol_forward.xmi");
	}
}